package com.appengine.news.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.appengine.news.Constants;

/**
 * Application config
 * 
 * @author Aliaksandr_Spichakou
 * 
 */
public class Config implements Constants{
	private static final Logger log = Logger.getLogger(Config.class
			.getName());
	private static Config instance;
	private static final String APP_URL = "app.url";
	private static final String STORE_EMAIL = "store.email";
	private static final String POST_EMAIL = "post.email";
	private static final String ADMIN_EMAIL = "admin.email";
	private List<String> emails;
	
	private Properties config = new Properties();
	private Config() {
		try {
			config.load(getClass().getResourceAsStream(CONFIG_PATH));
		} catch (IOException e) {
			log.log(Level.SEVERE,"Cannot load config file",e);
		}
	}
	/**
	 * Get confing instance
	 * @return
	 */
	public static Config getInstance()
	{
		if(instance==null)
		{
			instance = new Config();
		}
		return instance;
	}
	/**
	 * Get admin email
	 * @return
	 */
	public String getAdminEmail()
	{
		return config.getProperty(ADMIN_EMAIL);
	}
	/**
	 * Get application url
	 * @return
	 */
	public String getAppUrl()
	{
		return config.getProperty(APP_URL);
	}
	/**
	 * Get store email
	 * @return
	 */
	public String getStoreEmail()
	{
		return config.getProperty(STORE_EMAIL);
	}
	/**
	 * Get Post email
	 * @return
	 */
	public String getPostEmail(String mail)
	{
		return config.getProperty(POST_EMAIL+mail);
	}
	/**
	 * Get emails
	 * @return
	 */
	public List<String> getPostEmail()
	{
		if(emails==null || emails.isEmpty())
		{
			emails=new ArrayList<String>();
			final Set<Entry<Object, Object>> entrySet = config.entrySet();
			final Iterator<Entry<Object, Object>> iterator = entrySet.iterator();
			while(iterator.hasNext())
			{
				final Entry<Object, Object> next = iterator.next();
				final String key = (String)next.getKey();
				if(key.startsWith(POST_EMAIL))
				{
					emails.add((String)next.getValue());
				}
			}
		}
		
		return emails;
	}
}
